package com.ada.secure;

import jodd.util.Base64;

import java.security.*;

public class SignApp {

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        // 生成密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();

// 数据
        String data = "Hello, World!";
        byte[] dataBytes = data.getBytes();

// 数字签名
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(dataBytes);
        byte[] digitalSignature = signature.sign();
        System.out.println(Base64.encodeToString(digitalSignature));


        // 使用发送端的公钥来验证签名
        Signature signature1 = Signature.getInstance("SHA256withRSA");
        signature1.initVerify(publicKey);
        signature1.update(dataBytes);
        boolean verified = signature1.verify(digitalSignature);

        if (verified) {
            System.out.println("数字签名验证成功，数据完整性验证通过");
        } else {
            System.out.println("数字签名验证失败，数据可能被篡改");
        }
    }
}
